package com.guyaogg.gulimall.order.web;

import com.guyaogg.gulimall.order.service.OrderService;
import com.guyaogg.gulimall.order.vo.OrderConfirmVO;
import com.guyaogg.gulimall.order.vo.OrderSubmitVO;
import com.guyaogg.gulimall.order.vo.SubmitOrderResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.concurrent.ExecutionException;

/**
 * @author 顾遥
 */
@Slf4j
@Controller
public class OrderWebController {

    private final OrderService orderService;

    public OrderWebController(OrderService orderService) {
        this.orderService = orderService;
    }

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVO confirmVO = orderService.confirmOrder();

        // 展示订单确认
        model.addAttribute("orderConfirmData", confirmVO);
        return "confirm";
    }

    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVO vo, Model model, HttpSession session) {
        try {
            log.debug("页面采集信息：{}", vo);

            SubmitOrderResponseVO responseVO = orderService.submitOrder(vo);
            if (responseVO.getCode() == 0) {
                //下单成功
                model.addAttribute("submitOrderResp", responseVO);
                return "pay";
            }
            StringBuilder msg = new StringBuilder("下单失败：");
            switch (responseVO.getCode()) {
                case 1:
                    msg.append("订单信息过期，请刷新再次提交");
                    break;
                case 2:
                    msg.append("订单商品价格发送变化，请确认后提交");
                    break;
                case 3:
                    msg.append("库存锁定失败，商品库存不足");
                    break;
                default:
                    msg.append("内部服务器未知错误，请重试");
            }
            // TODO 阿里的 fastjson 不能使用 addFlashAttribute
//        redirectAttributes.addFlashAttribute("msg", msg.toString());
            session.setAttribute("payMsg", msg.toString());
            return "redirect:http://order.gulimall.com/toTrade";
        } catch (Exception e) {
            // TODO 分布式事务回滚，报错方式
            session.setAttribute("payMsg", e.getMessage());
            return "redirect:http://order.gulimall.com/toTrade";
        }


    }
}
